package com.czh.subject.application.Interceptor;

import com.czh.subject.common.constants.UserConstant;
import com.czh.subject.common.context.UserContextHandler;
import com.czh.subject.common.utils.UserUtil;
import io.micrometer.common.util.StringUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import reactor.util.annotation.NonNull;

import java.io.IOException;

/**
 * 登录拦截器
 *
 * @author caozaihui
 * @version 1.0
 * @since 2024/9/7 下午 7:53
 */
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, @NonNull HttpServletResponse response,@NonNull Object handler) throws IOException {
        String loginId = request.getHeader(UserConstant.USER_CONTEXT_ID);
        if (StringUtils.isBlank(loginId)) {
            log.error("---->登录信息为空<----");
            response.setStatus(500);
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().print("你再盗用别人Token试试?");
            return false;
        }
        UserUtil.setUserId(loginId);
        return true;
    }

    @Override
    public void afterCompletion(@NonNull HttpServletRequest request,@NonNull HttpServletResponse response,@NonNull Object handler, Exception ex) throws Exception {
        UserContextHandler.remove();
    }
}
